package com.chookss.home.running;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.RunningRankEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.chookss.view.InitDialog;
import com.chookss.view.listener.ShareDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

public class RunningHomeActivity extends BaseAct implements SensorEventListener {
//请假记录列表

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_iv_ll)
    LinearLayout common_right_iv_ll;
    @BindView(R.id.common_right_iv)
    ImageView common_right_iv;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private RunningHomeAdapter adapter;
    private List<RunningRankEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    Sensor stepDetector;
    SensorManager mSensorManager;
    private int mStepCount = 0;//系统开机以来的总步数
    private int moveTodayNum = 0;//今日步数
    private boolean hasPermission = false;//是否拥有获取本地运动数据的权限
    private boolean toWechat = false;//跳轉微信或者只是單純開始刷新去了
    private boolean isFirst = true;//是否第一次  要调用两遍第一遍只是为了获取moveTodayNum
    private String employeeCode = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_running_home);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        employeeCode = new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
        LinearLayout.LayoutParams ivParams = (LinearLayout.LayoutParams) common_right_iv.getLayoutParams();
        ivParams.height = Utils.dip2px(this, 20);
        ivParams.width = Utils.dip2px(this, (float) 16.5);
        common_right_iv.setLayoutParams(ivParams);
        common_right_iv.setBackgroundResource(R.drawable.biaoqian_icon);
        NavigationTools.saveUseRecord(this, "1", "34");
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) smrRf.getLayoutParams();
        params.setMargins(0, Utils.dip2px(this, 15), 0, 0);
        smrRf.setLayoutParams(params);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new RunningHomeAdapter(R.layout.item_running_home, this, list);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        commonTitleTxt.setText("计步器");
        tvNone.setText("暂无步数记录");
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                if (isFirst || toWechat) {
                    getData();
                } else {
                    uploadData(1);
                }
            }
        });
        getPermission();
        smrRf.autoRefresh();
    }

    private void getPermission() {
        XXPermissions.with(this)
                .permission(Permission.ACTIVITY_RECOGNITION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            hasPermission = true;
                            initSensor();
                        } else {
                            PermissionUtils.errorPermission(RunningHomeActivity.this, granted, all);
                        }
                        initRunning();
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(RunningHomeActivity.this, denied, quick);
                        initRunning();
                    }
                });
    }

    private void initSensor() {
        // 获取SensorManager管理器实例
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        stepDetector = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if (stepDetector != null) {
            // 如果sensor找到，则注册监听器
            mSensorManager.registerListener(this, stepDetector, 1000000);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (toWechat) {
            Observable.timer(800, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) {
                            smrRf.autoRefresh();
                        }
                    });
        }
    }

    private void initRunning() {
        //判断当天是否跳转微信运动获取过数据 名是code_running_count   值是2022-12-26==1000
        String data = new ShareUtils().getString(this, employeeCode + "_running_count", "");
        if (Utils.isNull(data)) {
            //从未打开过微信运动
            showDialog(employeeCode);
        } else {
            String[] datas = data.split("==");
            if (datas.length > 1) {
                if (datas[0].equals(Utils.getCurrentTime2().substring(0, 10))) {
                    //当天
                } else {
                    //新的一天
                    showDialog(employeeCode);
                }
            }
        }
    }

    private void showDialog(String code) {
        new InitDialog(RunningHomeActivity.this,
                "提示", "跳转微信获取运动步数", "确定", true,
                new ShareDialogListener() {
                    @Override
                    public void onClick() {
                        toWechat = true;
                        NavigationTools.openMiniProgram(RunningHomeActivity.this, "pages/index/index?employeeCode=" + employeeCode);
                        new ShareUtils().putString(RunningHomeActivity.this, code + "_running_count", Utils.getCurrentTime2().substring(0, 10) + "==isUpload");
                    }
                }).show();
    }

    private void getData() {
        //-1不用管运动的 1需要处理  2也不需要处理
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RunningRankEntity>>>() {
        }.getType(), null, Urls.selectMoveLvlList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<RunningRankEntity>>() {
            @Override
            public void onSuccess(List<RunningRankEntity> data) {
                dismissLoading();
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }

                int old = list.size();
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(old, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                    moveTodayNum = Utils.changeNumber(list.get(0).getMoveNum());
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                }
                String runningCount = new ShareUtils().getString(RunningHomeActivity.this, employeeCode + "_running_count", "");
                if (toWechat) {
                    if (list.size() > 0) {
                        if (list.get(0).getCreateTime().equals(Utils.getCurrentTime2().substring(0, 10))) {
                            if(!Utils.isNull(runningCount)){
                                if(runningCount.contains("reStart")||mStepCount < moveTodayNum || mStepCount == 0){
                                    //当天重启过
                                    new ShareUtils().putString(RunningHomeActivity.this, employeeCode + "_running_count", Utils.getCurrentTime2().substring(0, 10)  + "==reStart=="  + moveTodayNum + "==" + mStepCount);
                                }else{
                                    new ShareUtils().putString(RunningHomeActivity.this, employeeCode + "_running_count", Utils.getCurrentTime2().substring(0, 10) + "==" + moveTodayNum + "==" + mStepCount);
                                }
                            }else{
                                new ShareUtils().putString(RunningHomeActivity.this, employeeCode + "_running_count", Utils.getCurrentTime2().substring(0, 10) + "==" + moveTodayNum + "==" + mStepCount);
                            }
                        } else {
                            //异常情况 第一条数据不是当天
                            new ShareUtils().putString(RunningHomeActivity.this, employeeCode + "_running_count", Utils.getCurrentTime2().substring(0, 10) + "==" + 0 + "==" + mStepCount);
                        }
                    } else {
                        //异常情况 第一条数据不是当天
                        new ShareUtils().putString(RunningHomeActivity.this, employeeCode + "_running_count", Utils.getCurrentTime2().substring(0, 10) + "==" + 0 + "==" + mStepCount);
                    }
                    toWechat = false;
                }
                if (isFirst) {
                    isFirst = false;
                    if (!Utils.isNull(runningCount)) {
                        String[] datas = runningCount.split("==");
                        if (datas.length > 1) {
                            if (datas[0].equals(Utils.getCurrentTime2().substring(0, 10))) {
                                //当天
                                uploadData(2);
                            }
                        }
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    // 1无论如何需要刷新列表数据，2的情况下只有本地数据更新了才需要去更新列表数据
    private void uploadData(int type) {
        int moveNum = 0;
        KLog.i(moveTodayNum + "==" + mStepCount + "==" + hasPermission);
        String data = new ShareUtils().getString(this, employeeCode + "_running_count", "");
        if (!hasPermission) {
            //沒有權限
            if (type == 1) {
                getData();
            }
            return;
        }
        if (Utils.isNull(data)) {
            //异常
            if (type == 1) {
                getData();
            }
            return;
        } else {
            String[] datas = data.split("==");
            if (datas.length > 1) {
                if (datas[0].equals(Utils.getCurrentTime2().substring(0, 10))) {
                    //当天
                    if ("isUpload".equals(datas[1])) {
                        KLog.i("包含isUpload");
                        new ShareUtils().putString(RunningHomeActivity.this, employeeCode + "_running_count", Utils.getCurrentTime2().substring(0, 10) + "==" + moveTodayNum + "==" + mStepCount);
                        if (type == 1) {
                            getData();
                        }
                        return;
                    } else if ("reStart".equals(datas[1])) {
                        KLog.i("包含reStart");
                        //当天重启系统或者手机了导致数据不准停止上传
                        int cacheTodayNum = Utils.changeNumber(datas[2]);
                        int cacheStepCount = Utils.changeNumber(datas[3]);
                        moveNum = cacheTodayNum + (mStepCount - cacheStepCount);
                        if(moveNum==moveTodayNum){
                            return;
                        }
                    } else {
                        if (mStepCount < moveTodayNum || mStepCount == 0) {
                            KLog.i("不包含reStart");
                            //当天重启系统或者手机了导致数据不准停止上传
                            new ShareUtils().putString(RunningHomeActivity.this, employeeCode + "_running_count", Utils.getCurrentTime2().substring(0, 10) + "==reStart==" + moveTodayNum + "==" + mStepCount);
                            if (type == 1) {
                                getData();
                            }
                            return;
                        }else{
                            KLog.i("正常处理");
                            int cacheTodayNum = Utils.changeNumber(datas[1]);
                            int cacheStepCount = Utils.changeNumber(datas[2]);
                            if (mStepCount <= cacheStepCount) {
                                //异常或者一样，就没必要去更新了
                                if (type == 1) {
                                    getData();
                                }
                                return;
                            }
                            moveNum = cacheTodayNum + (mStepCount - cacheStepCount);
                            if(moveNum==moveTodayNum){
                                return;
                            }
                        }

                    }
                } else {
                    if (type == 1) {
                        getData();
                    }
                    return;
                }
            } else {
                //异常
                if (type == 1) {
                    getData();
                }
                return;
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("moveNum", moveNum + "");
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.updateMoveEmpNum, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                } else {
                    MyToast.show(reObject.getString("msg"));
                }
                showLoading();
                isEnd = false;
                currentPage = 1;
                getData();
            }

            @Override
            public void onError(String errorMsg) {
                getData();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
//        if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
//            //app启动以来监听事件的步数
//            if (event.values[0] == 1.0f) {
//                mStepDetector++;
//            }
//        }
        if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
            //APP开机以来计步器总步数事件
            mStepCount = (int) event.values[0];
        }
        KLog.i(mStepCount + "==========");
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    //提示用户手动开启权限
                    new AlertDialog.Builder(this)
                            .setTitle("健康运动权限")
                            .setMessage("健康运动权限不可用")
                            .setPositiveButton("立即开启", (dialog12, which) -> {
                                // 跳转到应用设置界面
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivityForResult(intent, 123);
                            })
                            .setNegativeButton("取消", (dialog1, which) -> {
                                initRunning();
                            }).setCancelable(false).show();
                } else {
                    hasPermission = true;
                    initSensor();
                }
            }
        }
    }

    class RunningHomeAdapter extends BaseQuickAdapter<RunningRankEntity, BaseViewHolderEx> {
        private Activity context;
        private int type = 7; //7报销记录  9借款记录10补贴记录

        public RunningHomeAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<RunningRankEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, RunningRankEntity entity) {
            TextView tvTime = helper.getView(R.id.tvTime);
            TextView tvRank = helper.getView(R.id.tvRank);
            TextView tvCount = helper.getView(R.id.tvCount);
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            GlideUtils.loadAvatar(context, entity.getFirstHeadPhotoThumbUrl(), ivHead);
            TextView tvName = helper.getView(R.id.tvName);
            tvName.setText(entity.getFirstEmployeeName() + "夺得" + entity.getCreateTime() + "排行榜冠军");
            tvTime.setText(entity.getCreateTime());
            tvRank.setText(entity.getRankNum());
            tvCount.setText(Utils.changeNumber(entity.getMoveNum()) + "");

            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if (helper.getItemPosition() == 0) {
                        uploadData(2);
                    }
                    Intent intent = new Intent(context, RunningRankActivity.class);
                    intent.putExtra("createTime", entity.getCreateTime());
                    context.startActivity(intent);
                }
            });
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.right_question_ll, R.id.common_right_iv_ll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.right_question_ll:
                new InitDialog(RunningHomeActivity.this,
                        "提示", "跳转微信获取实时运动步数", "确定", true,
                        new ShareDialogListener() {
                            @Override
                            public void onClick() {
                                toWechat = true;
                                NavigationTools.openMiniProgram(RunningHomeActivity.this, "pages/index/index?employeeCode=" + employeeCode);
                            }
                        }).show();
                break;
            case R.id.common_right_iv_ll:
                Intent intent = new Intent(this, RunningActivityActivity.class);
                startActivity(intent);
                break;
        }
    }
}
